package com.bdqn.reflect;

import com.bdqn.reflect.pojo.Person;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * 测试4-获取类的属性
 *
 * @author LILIBO
 * @since 2024/6/27
 */
public class Test04Field {

    public static void main(String[] args) {
        try {
            Person hongshuai = new Person("红帅"); // 创建一个对象：红帅
            Person junyi = new Person("俊毅");
            Class clazz = Person.class;
            // 能获取非public属性
            Field name = clazz.getDeclaredField("name");
            // 跨访问修饰符访问
            name.setAccessible(true);
            System.out.println("[hongshuai]对象的name属性值为：" + name.get(hongshuai));
            System.out.println("[junyi]对象的name属性值为：" + name.get(junyi));
            System.out.println();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                // 属性的访问修饰符
                int modifier = field.getModifiers();
                String modifierStr = "";
                if ((modifier & Modifier.PUBLIC) == Modifier.PUBLIC) {
                    modifierStr = "public";
                } else if ((modifier & Modifier.PRIVATE) == Modifier.PRIVATE) {
                    modifierStr = "private";
                } else if ((modifier & Modifier.PROTECTED) == Modifier.PROTECTED) {
                    modifierStr = "protected";
                } else {
                    modifierStr = "default(package)";
                }

                if ((modifier & Modifier.STATIC) == Modifier.STATIC) {
                    modifierStr += " static";
                }
                if ((modifier & Modifier.FINAL) == Modifier.FINAL) {
                    modifierStr += " final";
                }
                if ((modifier & Modifier.ABSTRACT) == Modifier.ABSTRACT) {
                    modifierStr += " abstract";
                }
                // 属性的名称
                String fieldName = field.getName();
                // 属性的类型
                Class fieldType = field.getType();

                // 打印类的所有属性
                System.out.println(modifierStr + " " + fieldType.getSimpleName() + " " + fieldName + ";");
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.fillInStackTrace();
        }

    }

}
